package com.wlstock.funi.MissionInstance;

import android.content.Context;

import com.android.volley.VolleyError;
import com.em.mission.Mission;
import com.em.mission.MissionItem;
import com.em.mission.MissionListener;
import com.em.mission.MissionResultListener;
import com.maxleap.MLDataManager;
import com.maxleap.MLObject;
import com.maxleap.SaveCallback;
import com.maxleap.exception.MLException;
import com.wlstock.funi.R;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.dao.StrategyDao;
import com.wlstock.funi.dao.StrategyFundSelDao;
import com.wlstock.funi.model.StrategyFundModel;
import com.wlstock.funi.model.StrategyModel;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.request.WenGuRequest;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.ToastUtils;

import org.apache.cordova.LOG;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

/**
 * Created by admin on 16/8/30.
 */

public class StrategyMission extends MissionItem implements MissionListener, NetWorkListener {

    private static StrategyMission daoInstance;
    private Stack<StrategyModel> strategyModels;
    private WenGuRequest straWGRequest;
    private int strategyModelsCount;
    private boolean isSearchStrategy;
    private static final String STRATEGY_REQ = "STRATEGY_REQ";
    private List<StrategyFundModel> strategyFundModels;



    private StrategyMission(Context mContext,String name){
        super(mContext, name);
        strategyModels = getStragtegyModels();
        strategyModelsCount = strategyModels.size();
        isSearchStrategy  = false;
        retryTime         = 0;
        strategyFundModels = new ArrayList<StrategyFundModel>();
    }


    public static StrategyMission getInstance(Context mContex,String name){
        if (daoInstance == null){
            synchronized (StrategyMission.class){
                if (daoInstance == null){
                    daoInstance = new StrategyMission(mContex,name);
                }
            }
        }
        return daoInstance;
    }

    

    public void start(String missionName,MissionResultListener resultListener){
        this.resultListener = resultListener;
        this.missionName = missionName;
        start(this, resultListener);
    }

    @Override
    public void beforeExecuteListener(Mission mission) {

    }

    @Override
    public void onExecute(Mission mission) {
        if (strategyModelsCount!=0 && !isSearchStrategy){
            isSearchStrategy = true;
            StrategyModel topModel = strategyModels.peek();
            if (topModel != null){
                reqStra(topModel.getFullName(), STRATEGY_REQ);
            }
        }
    }

    @Override
    public void afterExecute(Mission mission) {

    }

    public void reqStra(String key, String tag){
        if (straWGRequest == null){
            straWGRequest = new WenGuRequest();
        }
        straWGRequest.netWorkListener = this;
        straWGRequest.request(key, tag);
    }


    private Stack<StrategyModel> getStragtegyModels() {
        List<StrategyModel> strategyModels = StrategyDao.getInstance(mContext).queryNeedToSearch();
        Stack<StrategyModel> stackModels = new Stack<StrategyModel>();
        if (!strategyModels.isEmpty()){
            for (int i = 0; i < strategyModels.size(); i++){
                stackModels.add(strategyModels.get(i));
            }
        }
        return stackModels;
    }

    @Override
    public void onErrorResponse(VolleyError error, String eventCode) {
        retryTime++;
        if (STRATEGY_REQ.equals(eventCode)){
            if (retryTime < maxRetryTime){
                isSearchStrategy = false;
                onExecute(this);
            }else{
                if (resultListener!=null){
                    resultListener.executeFaile(this);
                }
            }
        }
    }

    @Override
    public void onResponse(String response, String eventCode) {
        if (STRATEGY_REQ.equals(eventCode)){
            FundAsyTask<String, Void, HashMap<String, Object>> task = new FundAsyTask<String, Void, HashMap<String, Object>>();
            task.backListener = new FundAsyTask.TaskLitener<String, HashMap<String, Object>>() {
                @Override
                public HashMap<String, Object> doInBackground(String... params) {
                    return StockUtils.parseWenguTableData(params[0]);
                }
            };
            task.resultListener = new FundAsyTask.TaskResultListener<HashMap<String, Object>>() {
                @Override
                public void onPostResult(HashMap<String, Object> result) {
                    String stkName = "无数据";
                    String stkNo = "";
                    StrategyFundModel strategyFundModel = new StrategyFundModel(strategyModels.peek());
                    if (result != null) {
                        String[] titles = (String[]) result.get(StockUtils.KEY_TITLE);
                        ArrayList<ArrayList<String>> results = (ArrayList<ArrayList<String>>) result.get(StockUtils.KEY_RESULT);
                        if (results != null && !results.isEmpty()) {
                            String count = (String) result.get(StockUtils.KEY_COUNT);
                            ArrayList<String> firstItem = results.get(0);
                            if (firstItem != null && firstItem.size()>2){
                                stkNo = StockUtils.getSimpleStkCode(firstItem.get(0));
                                stkName = firstItem.get(1);
                            }
                        }
                    }
                    strategyFundModel.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    strategyFundModel.setStkNo(stkNo);
                    strategyFundModel.setStkName(stkName);
                    strategyFundModels.add(strategyFundModel);

                    StrategyFundSelDao.getInstance(mContext).createOrUpdate(strategyFundModel);

                    NotiUtils.showSimpleNoti(mContext, NotiIdGenerator.ID_STRATEGYFUND,strategyFundModel.getStrategyShortName()+"加入成功",strategyFundModel.getStkName()+"("+strategyFundModel.getStkNo()+")", R.drawable.ic_ai);
                    strategyModelsCount --;
                    strategyModels.pop();
                    if (!strategyModels.isEmpty()){
                        StrategyModel curTopModel = strategyModels.peek();
                        reqStra(curTopModel.getFullName(), STRATEGY_REQ);
                    }else{
                        isSearchStrategy = false;
                        NotiUtils.showSimpleNoti(mContext, NotiIdGenerator.ID_STRATEGYFUND,"完成所有策略加入","完成所有策略加入",R.drawable.ic_ai);
                        saveStrategyModels(strategyFundModels);
                        if (resultListener!=null){
                            resultListener.executeSuccess("OK", StrategyMission.this);
                        }
                    }
                }
            };
            task.execute(response);
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {

    }

    @Override
    public void onResponse(String response, EventBusConstants eventCode) {

    }


    private void saveStrategyModels(List<StrategyFundModel> strategyFundModels) {
        if (strategyFundModels==null || strategyFundModels.isEmpty()) return;

        List<MLObject> mlObjects = new ArrayList<>();
        for (int i = 0 ; i<strategyFundModels.size(); i++){
            MLObject mlObject = strategyFundModels.get(i).coverToMLObj();
            mlObjects.add(mlObject);
        }
        MLDataManager.saveAllInBackground(mlObjects, new SaveCallback() {
            @Override
            public void done(MLException e) {
                if (e == null){
                    LOG.i("TAG", "创建成功");
                    ToastUtils.showMiddleMsg(mContext, "上传MAXLEAP成功");
                }else{
                    LOG.i("TAG", "创建失败");
                    ToastUtils.showMiddleMsg(mContext, "上传MAXLEAP失败");
                }
            }
        });
    }

}
